<?php

class Itc_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
	/**
     * Zend_Auth object
     * @var Zend_Auth
	 */
	private $auth;

	/**
	 * Itc_Acl object
	 * @var Itc_Acl
	 */
	private $acl;

	/**
	 * Constructor
	 *
	 * @param Itc_Acl $acl acl object
	 * @return void
	 */
	public function __construct($acl)
	{
		$this->auth = Zend_Auth::getInstance();
		$this->acl  = $acl;
	}

	/**
	 * (non-PHPdoc)
	 * @see library/Zend/Controller/Plugin/Zend_Controller_Plugin_Abstract#preDispatch($request)
	 */
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		$view	= Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view;
		
		//Auth part
		if ($this->auth->hasIdentity()) {
			$identity			= $this->auth->getStorage()->read();
			$role				= 'doctor';
			$view->currentUser	= (array)$identity;
		}
    	else{
    		$role	= 'guest';
    	}
    	$view->userRole	= $role;
    	
    	//Acl part
		$module		= $request->getModuleName();
		$module		= ($module == 'default') ? '' : $module . "_";
        $resource	= $request->getControllerName();
        $action		= $request->getActionName();

		if(!$this->acl->isAllowed($role, $module.$resource, $action)){
            $request->setModuleName('default')
            		->setControllerName('error')
            		->setActionName('denied');
        }
	}
	
	/**
	 * Return ACL
	 */
	public function getAcl()
	{
		return $this->acl;
	}
}
